#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import re
# import json

def voteSomebody(number):
    url = r'http://campus.finance365.com/Rematch/UserCenter/'+str(number)
    a = requests.Session()
    a.headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36'
    try:
        html = a.get(url).content
        votes = get_vote(html)
        user_info = get_username_and_where(html)
        user_id = get_user_id(html)
    except :
        print 'Please Check You Network. Something wrong with your network'
        raw_input('')
        exit(-1)
    # print a.cookies.get('cVote')
    jsondata = { 'user_id': user_id, 'aid': "8wwc"  }
    # hid = re.findall('val = "([^"]+)"', html)[0]
    # jsondata = { 'user_id': user_id, 'hid': hid}
    try:
        result = a.post(r'http://campus.finance365.com/Rematch/Handler', params=jsondata).text
        print result
        print user_info[1], '-', user_info[0], ': ', votes
    except :
        print 'Please Check You Network. Something wrong with your network'
        raw_input()
        exit(-1)

def get_vote(html):
    vote_message = re.findall('<i></i>([^"]+)</a>', html)[0]
    return vote_message

def get_username_and_where(html):
    username = re.findall('<strong class="user_name">([^"]+)</strong> <span class="user_address">([^"]+)</span>', html)[0]
    return username

def get_user_id(html):
    user_id = re.findall('var user_id = "([^"]+)";', html)[0]
    return user_id

if __name__ == '__main__':
    import time
    from random import randint
    times = raw_input("How many votes for Xiaoyingzi?: ")

    if not times.isdigit():
        print "Input Error. Please retry."
        raw_input()
        exit(0)

    for i in range(int(times)):
        print 'waiting ....'
        # get('201405281656426790', r'http://campus.finance365.com/Rematch/UserCenter/47')
        voteSomebody(47)
        seconds = randint(13, 45)
        print 'Had voted ',i+1,' votes'
        print 'after '+ str(seconds)+' seconds vote the ' + str(i+2) + ' vote'
        print 'waiting ....'
        print ""
        time.sleep(seconds)
